﻿using AnalyStock.DataManage;

namespace AnalyStock.GrapImage;

public partial class ChartKline : UserControl
{
    private bool isFillF10Panel = true;

    /// <summary>
    ///     初始化，加载股票备份数据
    /// </summary>
    public ChartKline()
    {
        InitializeComponent();
        InitializePanel_QueryStockCode();
        InitializePanel_ChartMintue();
        InitializeSeleStockMenu();
        InitializeKline();
    }

    /// <summary>
    ///     改变面板头显示股票名称
    /// </summary>
    /// <returns></returns>
    private void TextHeaderItem()
    {
        StockNameItem.Text = $"{currStockInfo.Name}\n{currStockInfo.Ts_code}";
        StockNoteItem.Text = $"产品/概念: {currStockInfo.Note?.Split("\n").FirstOrDefault().TrimEnd()}";
        TextBoxStockNote.Text = currStockInfo?.Note;
    }

    /// <summary>
    ///     加载交易数据，生成蜡烛线数据
    /// </summary>
    /// <returns></returns>
    private void PaintCandelPanel(KlineData kdata)
    {
        ChartCandle.ChartCandleChanged(ref kdata, currPeriodType); //画K线图
    }

    /// summary
    /// 生成F10面板的财务指标数据
    /// </summary>
    /// <param name="bakDaily"></param>
    /// <param name="finanIndexs"></param>
    /// <returns></returns>
    private void PaintF10Panel(KlineData kData)
    {
        FinancialIndexPanel.Children.Clear();
        TextBakInfor(kData.StockInfo); //显示股票面板属性数据
        TextFinanIndex(kData.Financials); //显示主要财务指标数据
    }

    private void TextBakInfor(StockInfo bakDaily)
    {
        new TextBlock
        {
            Text = string.Join("\n", bakDaily.ToShowValue()),
            Width = 132,
            Style = SetElementStyle("TextBlockStyle")
        }.WithPanel(FinancialIndexPanel);
    }

    private void TextFinanIndex(IList<FinancialIndex> financials)
    {
        //如果没有筛选指标返回
        if (financials.IsNullOrEmpty())
        {
            return;
        }
        //显示分项题头       

        new TextBlock
        {
            Text = string.Join("\n", FinancialIndex.GetPropertyChineseName()),
            Width = 140,
            Style = SetElementStyle("TextBlockStyle")
        }.WithPanel(FinancialIndexPanel);
        //显示最新财务指标值
        new TextBlock
        {
            Text = string.Join("\n", financials.Last().GetValueArray()),
            Width = 65,
            Style = SetElementStyle("TextBlockStyle")
        }.WithPanel(FinancialIndexPanel);

        //显示最新指标的增长速度
        if (financials.Count > 4 && financials[^5] is not null) //上年同期
        {
            var curretFinanidx = financials.Last().GetValueArray();
            var lastyearFinanidx = financials[^5].GetValueArray();
            var increaseFinanidx = new string[curretFinanidx.Length];

            for (var i = 0; i < curretFinanidx.Length; i++)
            {
                increaseFinanidx[i] = i < 1
                    ? "同比增长"
                    : $"{((float)curretFinanidx[i] / (float)lastyearFinanidx[i]) - 1:P1}";
            }

            new TextBlock
            {
                Text = string.Join("\n", increaseFinanidx),
                Width = 55,
                Style = SetElementStyle("TextBlockStyle")
            }.WithPanel(FinancialIndexPanel);
        }

        //显示财务指标历史数据
        for (var i = financials.Count - 2; i >= 0; i--)
        {
            new TextBlock
            {
                Text = string.Join("\n", financials[i].GetValueArray()),
                Width = 65,
                Style = SetElementStyle("TextBlockStyle")
            }.WithPanel(FinancialIndexPanel);
        }
    }

    /// <summary>
    ///     K线图周期类型变化
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    #region
    private void ChangeDateType_Click(object sender, RoutedEventArgs e)
    {
        if (currStockInfo is null) { return; }
        var _button = sender as Button;
        currPeriodType = _button switch
        {
            { Name: nameof(BtnDailyData) } => CandlePointSet.PeriodType.Daily,
            { Name: nameof(BtnWeekData) } => CandlePointSet.PeriodType.Weekly,
            { Name: nameof(BtnMonthData) } => CandlePointSet.PeriodType.Monthly,
            _ => currPeriodType
        };

        if (_button.Name != nameof(BtnMintueData))
        {
            RefreshBtnStyle();
            RefreshKlineData(DaysChangeType.IniDays);
        }
        else
        {
            MintuePricePanel_OpenToClose();
            RefreshKlineData(DaysChangeType.NoChange);
        }
        return;
        void RefreshBtnStyle()
        {
            new[] { BtnDailyData, BtnWeekData, BtnMonthData }
                .ForEachDo(n => n.Style = SetElementStyle("ButtonStyle"));
            _button.Style = SetElementStyle("ButtonWarmStyle");
        }
    }

    #endregion

    /// <summary>
    ///     K线变化，重新画K线和F10指标
    /// </summary>

    #region

    private async void InitializeKline()
    {
        Filled_KlineData += KlineChanged;
        InitializeKlineMouseEvent();
        await FillAllStockInfosAsync();
    }

    private void InitializeSeleStockMenu()
    {
        InitializeMenu_ConceptionClassify();
        InitializeMenu_SeleStockNote();
    }

    private void KlineChanged(object sender, KlineData klineData)
    {
        if (currStockInfo is not null)
        {
            TextHeaderItem();
        }

        if (!klineData.Dailies.IsNullOrEmpty())
        {
            PaintCandelPanel(klineData); //画蜡烛线            
        }

        if (!klineData.MinuteDatas.IsNullOrEmpty())
        {
            PaintMintuePanel();
        }

        if (!klineData.Financials.IsNullOrEmpty())
        {
            PaintF10Panel(klineData); //财务指标
        }
    }

    #endregion

    /// <summary>
    ///     技术指标图
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>

    #region

    private void ChartPriceLine_Click(object sender, RoutedEventArgs e)
    {
        var _btnName = (sender as Button).Name;
        ChartCandle.IsMa2line = _btnName.Equals(nameof(BtnMA2)) && !ChartCandle.IsMa2line;
        ChartCandle.IsMa4line = _btnName.Equals(nameof(BtnMA4)) && !ChartCandle.IsMa4line;
        ChartCandle.IsBollLine = _btnName.Equals(nameof(BtnBOLL)) && !ChartCandle.IsBollLine;
        ChartCandle.IsFibonacciLine = _btnName.Equals(nameof(BtnFBNAC)) && !ChartCandle.IsFibonacciLine;
        ChartCandle.IsTrendLine = _btnName.Equals(nameof(BtnTrendLine)) && !ChartCandle.IsTrendLine;
        try
        {
            ChartCandle.PaintLine_MainChart();
        }
        catch (Exception ex)
        {
            ex.Message.ErrorMessage();
        }
    }

    private void ChartKlineIndex_Click(object sender, RoutedEventArgs e)
    {
        var nameButton = (sender as Button).Name;
        ChartCandle.IsMACD = nameButton.Equals(nameof(BtnMACD));
        ChartCandle.IsKDJ = nameButton.Equals(nameof(BtnKDJ));
        ChartCandle.IsPEPB = nameButton.Equals(nameof(BtnPEPB));
        ChartCandle.IsTurnOverRate = nameButton.Equals(nameof(BtnTurnOverRate));
        //ChartCandle.IsQQRatio = nameButton.Equals(nameof(BtnQRRatio));
        try
        {
            ChartCandle.PaintLine_AttachedChart();
        }
        catch (Exception ex)
        {
            ex.Message.ErrorMessage();
        }
    }

    private void ChangeF10Panel_Click(object sender, RoutedEventArgs e)
    {
        isFillF10Panel = !isFillF10Panel;
        F10IndexRow.Height = isFillF10Panel
            ? new GridLength(3.0, GridUnitType.Star)
            : new GridLength(0.0, GridUnitType.Star);
        ChartCandle.UpdateLayout();
    }

    private void OpenBrowser_Click(object sender, RoutedEventArgs e)
    {
        if (currStockInfo is null)
        {
            return;
        }

        CommAppMethod.OpenNetByBrowser(currStockInfo.Name);
    }

    #endregion
}